/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.scope;

import com.inspur.edp.bef.core.session.BEFuncSessionBase;
import com.inspur.edp.bef.core.session.FuncSession;
import com.inspur.edp.bef.core.session.FuncSessionManager;
import com.inspur.edp.cef.api.message.IBizMessage;
import com.inspur.edp.cef.api.scope.ICefScopeNodeParameter;
import com.inspur.edp.cef.spi.scope.AbstractCefScopeExtension;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

//相同paramter类型按be类型分开执行
public abstract class SingleBETypeExtension<T extends ScopeNodeParameter> extends
    AbstractCefScopeExtension {
  protected SingleBETypeExtension() {}

  private String privateCurrentBeType;

  protected final String getCurrentBeType() {
    return privateCurrentBeType;
  }

  private void setCurrentBeType(String value) {
    privateCurrentBeType = value;
  }

  protected List<T> getBEParameters() {
    return super.getParamsGeneric();
  }

  @Override
  public final void onSetComplete() {
    Map<Object, List<ICefScopeNodeParameter>> typeGroups = getBEParameters().stream().collect(
        Collectors.groupingBy(
            par -> ((ScopeNodeParameter) par).getBEContext().getBizEntity().getBEType()));
    for (Map.Entry<Object, List<ICefScopeNodeParameter>> group : typeGroups.entrySet()) {
      super.setParameters(group.getValue());
      setCurrentBeType((String)group.getKey());
      onExtendSetComplete();
    }
  }

  public void addMessage(IBizMessage... msgList){
    Objects.requireNonNull(msgList, "msgList");
    getSessionItem().getResponseContext().mergeMessage(Arrays.asList(msgList));
  }

  private FuncSession currSession;
  protected final BEFuncSessionBase getSessionItem(){
    if(currSession == null) {
      currSession = FuncSessionManager.getCurrentSession();
    }
    return currSession.getFuncSessionItem(getCurrentBeType());
  }

  public abstract void onExtendSetComplete();
}
